#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>

#define MAXLINE 4096

int main(int argc, char** argv)
{
        int socketfd, n;
        struct sockaddr_in serveraddr;
        char recvline[MAXLINE], sendline[MAXLINE];

        if (argc != 2) {
                printf("usage: ./client <ipaddress>\n");
                exit(0);
        }

        if ( (socketfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { // third param is 0,means select default protocol
                printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
                exit(0);
        }

        memset(&serveraddr, 0, sizeof(serveraddr));
        serveraddr.sin_family = AF_INET;
        serveraddr.sin_port = htons(8080);  // htonl: host to nel=====> htons: host to network u_short!!!
        if (inet_pton(AF_INET, argv[1], &serveraddr.sin_addr) <= 0) {
                printf("inet_pton error for %s \n", argv[1]);
                exit(0);
        }

        if ( connect(socketfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0) {
                printf("connect error: %s(errno:%d)\n", strerror(errno), errno);
                exit(0);
        }

        printf("=========send msg to server.....=====\n");

        while (fgets(sendline, MAXLINE, stdin) != NULL) {
                if (send(socketfd, sendline, strlen(sendline), 0) < 0) {
                        printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
                        exit(0);
                }
        }
        close(socketfd);
        return 0;
}
